package com.zx.club.wx.mp.handler;



import com.zx.club.wx.mp.builder.TextBuilder;
import com.zx.club.wx.redis.RedisUtil;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * 接收普通消息:文本消息、图片消息、语音消息、视频消息、小视频消息、地理位置消息、链接消息、推送事件等
 *
 * @author zx
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            // TODO 可以选择将消息保存到本地
        }

        // 当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                    && weixinService.getKefuService().kfOnlineList()
                    .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        // TODO 组装回复消息
        // String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);
        String content = "";
        if (!"验证码".equals(wxMessage.getContent())) {
            return new TextBuilder().build(content, wxMessage, weixinService);
        }
        String code = (int) ((Math.random() * 9 + 1) * 1000)+content;
        content = "【验证码】" + (int) ((Math.random() * 9 + 1) * 1000)+"! 五分钟有效";
        //验证码存放在redis中 key: openId.code
        redisUtil.setNx("loginCode."+code,wxMessage.getFromUser(),5L, TimeUnit.MINUTES);

        return new TextBuilder().build(content, wxMessage, weixinService);

    }



}
